#!/usr/bin/env python
import sys
from functools import wraps

def dataset ( func ):
	"""
	Decorator for dataset functions

	INPUT:
		- _X_START_POINT
		- _X_LINES
		- _X_PAGE

	The decorated func *must* accept two keyword argument:

		- limit
		- start_point

	And *must* return a dictionary with the following keys:

		- ``rows``: 	list of rows
		- ``tot_rows``: count of maximum number of rows
	"""
	@wraps ( func )
	def wrapped ( liwe, kwargs ):
		try:
			_X_START_POINT = int ( kwargs.get ( "_X_START_POINT", 0 ) )
		except:
			_X_START_POINT = 0

		try:
			_X_LINES = int ( kwargs.get ( "_X_LINES", 10 ) )
		except:
			_X_LINES = 10

		try:
			_X_PAGE = int ( kwargs.get ( "_X_PAGE", 0 ) )
		except:
			_X_PAGE = 0

		if "_X_START_POINT" in kwargs: del kwargs [ "_X_START_POINT" ]
		if "_X_LINES" in kwargs: del kwargs [ "_X_LINES" ]
		if "_X_PAGE" in kwargs: del kwargs [ "_X_PAGE" ]

		if _X_START_POINT:
			start_point = _X_START_POINT
		else:
			start_point = _X_PAGE * _X_LINES

		kwargs [ 'limit' ] = _X_LINES
		kwargs [ 'start_point' ] = start_point

		#import sys
		#sys.stderr.write ( "\n---- FUNC: %s\n" % func.__module__ )

		# FIXME: l'estrazione del nome del modulo (es. modules.news.ajax -> "news") 
		#        deve essere migliorato. Tra l'altro lo usiamo anche in una func delle liwe.py
		modname = func.__module__.split ( "." ) [ 1 ]
		result = liwe.command_execute ( modname, func, ** kwargs )
		#result = func ( liwe, ** kwargs )
		#sys.stderr.write ( "\n\n----------------------------------- DECORATORS: result type = %s\n" % type ( result ) )
		rows = result [ 'rows' ]
		tot_rows = result [ 'tot_rows' ]

		res = {}

		count = 0
		for v in rows:
			v [ "_pos" ] = start_point + count
			res [ "row%d" % count ] = v
			count += 1

		res [ 'rows' ] =  tot_rows
		res [ 'from_row' ] = start_point
		res [ 'to_row' ] = start_point + count
		res [ 'lines' ] = count # lines

		return res
		
	return wrapped
